package com.mi.interceptor;

import com.mi.util.LoginAnno;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//部分业务要求登录之后才能实现
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        //判断方法头上是否有自定义注解，如果有需要先登录，没有的话可以执行方法
        if(o instanceof HandlerMethod){     //判断o是否为HandlerMethod
            HandlerMethod hm = (HandlerMethod) o;

            //判断当前要执行的方法是否存在LoginAnno注解
            if(hm.hasMethodAnnotation(LoginAnno.class)){

                //从session中获取用户信息  如果为空代表没有登录需要先登录
                Object obj = httpServletRequest.getSession().getAttribute("user");

               if(null == obj){

                   httpServletResponse.sendRedirect("jump");

                   return false;
               }
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
